package	com.sdry.web.controller.llm;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sdry.model.llm.DeliveryNode;
import com.sdry.model.llm.DeliveryOutStock;
import com.sdry.model.lz.Car;
import com.sdry.model.lz.OutStockOrder;
import com.sdry.model.lz.OutStockOrderDetail;
import com.sdry.service.llm.DeliveryNodeService;
import com.sdry.service.lz.InventoryService;
import com.sdry.service.lz.StockOutOrderService;
import com.sdry.utils.Page;
import com.sdry.utils.ResponseUtil;

/**
 *
 *@ClassName: DeliveryNodeController
 *@Description: 配送单
 *@Author llm
 *@Date 2019-07-17 14:14:41
 *@version 1.0
*/
@Controller
@RequestMapping("/DeliveryNode")
public class DeliveryNodeController{
	
	@Resource 
	DeliveryNodeService deliveryNodeService;
	@Resource 
	StockOutOrderService stockOutOrderService;
	@Resource
	InventoryService inventoryService;
	
	/** 
	 * 进入页面
	 * @param model
	 * @return 页面路径
	*/
	@RequestMapping("/page")
	public ModelAndView pageDeliveryNode () {
		ModelAndView mv = new ModelAndView();
		List<Car> carList = stockOutOrderService.queryAllCar();
		mv.addObject("allCar", carList);
		mv.setViewName("/llm/deliveryNode");
		return mv;
	}
	/** 
	 * 根据主键id查询实体
	 * @param id 主键id
	 * @return 实体
	*/
	@RequestMapping("/queryById")
	@ResponseBody
	public DeliveryNode queryById(Long id) {
		DeliveryNode param = deliveryNodeService.queryById(id);
		return param;
	}
	/** 
	 * 条件查询所有
	 * @param param 实体条件
	 * @return 实体集合
	*/
	@RequestMapping("/queryAllByMution")
	@ResponseBody
	public List<DeliveryNode> queryAllByMution(DeliveryNode param) {
		List<DeliveryNode> list = deliveryNodeService.queryAllByMution(param);
		return list;
	}
	/** 
	 * 条件分页查询
	 * @param param 实体条件
	 * @param response
	 * @throws Exception
	*/
	@RequestMapping("/list")
	public void list(DeliveryNode param,HttpServletResponse response, HttpSession httpSession){
		Long warehouse_id = (Long) httpSession.getAttribute("warehouse_id");
		param.setWarehouse_id(warehouse_id);
		//条件分页查询内容
		List<DeliveryNode> list = deliveryNodeService.findPageByMution(param);
		//条件查询总条数
		Integer total = deliveryNodeService.selectCountByMution(param);
		//转为json数据传至页面
		JSONObject jsonObject = new JSONObject();
		JsonConfig jsonConfig = new JsonConfig();
		JSONArray jsonArray = JSONArray.fromObject(list, jsonConfig);
		jsonObject.put("code", 0);
		jsonObject.put("data", jsonArray);
		jsonObject.put("count", total);
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/** 
	 * 插入返回id
	 * @param param 实体条件
	 * @param response
	 * @throws Exception
	*/
	@RequestMapping("/insert")
	public void insert(DeliveryNode param, HttpServletResponse response, HttpSession httpSession){
		Long warehouse_id = (Long) httpSession.getAttribute("warehouse_id");
		param.setWarehouse_id(warehouse_id);
		Long id = deliveryNodeService.insert(param);
		try {
			ResponseUtil.write(response, id);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/** 
	 * 根据主键更新 返回影响行数
	 * @param param 实体条件
	 * @param response
	 * @throws Exception
	*/
	@RequestMapping("/update")
	public void update(DeliveryNode param,HttpServletResponse response){
		Integer count = deliveryNodeService.update(param);
		try {
			ResponseUtil.write(response, count);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/** 
	 * 根据主键拼接的字符串删除返回影响行数
	 * @param ids 主键拼接的字符串
	 * @return 影响行数
	*/
	@RequestMapping("/delete")
	public void delete(String ids,HttpServletResponse response){
		ids=ids.replace("'",""); 
		String[] temp = ids.split(",");
		for(int i=0;i<temp.length;i++) {
			List<DeliveryOutStock> lists= deliveryNodeService.queryoutstorkbydeliverid(Long.parseLong(temp[i]));
			for (DeliveryOutStock deliveryOutStock : lists) {
				deliveryNodeService.restorstatusbyoutid(deliveryOutStock.getOutStockId());
			}
			
		}
		Integer count = deliveryNodeService.delete(ids);
		try {
			ResponseUtil.write(response, count);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/** 
	 * 根据送货单ID查询出库单
	 * @param param 条件实体
	 * @param response
	 * @throws Exception
	*/
	@RequestMapping("/queryStockOutByDeliveryId")
	public void queryStockOutByDeliveryId(DeliveryOutStock param, HttpServletResponse response){
		//条件分页查询内容
		List<OutStockOrder> list = deliveryNodeService.queryStockOutByDeliveryId(param);
		//条件查询总条数
		Integer total = deliveryNodeService.selectCountStockOutByDeliveryId(param);
		//转为json数据传至页面
		JSONObject jsonObject = new JSONObject();
		JsonConfig jsonConfig = new JsonConfig();
		JSONArray jsonArray = JSONArray.fromObject(list, jsonConfig);
		jsonObject.put("code", 0);
		jsonObject.put("data", jsonArray);
		jsonObject.put("count", total);
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/** 
	 * 根据送货单ID查询出库单
	 * @param param 条件实体
	 * @param response
	 * @throws Exception
	*/
	@RequestMapping("/queryAllStockOut")
	public void queryAllStockOut(Page page, HttpServletResponse response, HttpSession httpSession){
		Long warehouse_id = (Long) httpSession.getAttribute("warehouse_id");
		page.setWarehouse_id(warehouse_id);
		//条件分页查询内容
		List<OutStockOrder> list = deliveryNodeService.queryAllStockOut(page);
		//条件查询总条数
		Integer total = deliveryNodeService.selectCountAllStockOut(warehouse_id);
		//转为json数据传至页面
		JSONObject jsonObject = new JSONObject();
		JsonConfig jsonConfig = new JsonConfig();
		JSONArray jsonArray = JSONArray.fromObject(list, jsonConfig);
		jsonObject.put("code", 0);
		jsonObject.put("data", jsonArray);
		jsonObject.put("count", total);
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**-------------------APP接口-------------APP接口-------------APP接口---------------APP接口---------------APP接口--------------*/
	/**
	 * 根据登录人查询所有配送单
	 * @param userId	登录人ID
	 * @param response
	 */
	@RequestMapping("/queryDeliveryByUid")
	public void queryDeliveryByUid(String userId, String warehouse_id, HttpServletResponse response){
		List<DeliveryNode> list = deliveryNodeService.queryDeliveryByUid(Long.parseLong(userId),Long.valueOf(warehouse_id));
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("status", "1");
		jsonObject.put("data", list);
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 根据登录人ID查询所有出库单
	 * @param userId	登录人ID
	 * @param response
	 */
	@RequestMapping("/queryOutStockByUserId")
	public void queryOutStockByUserId(String userId, HttpServletResponse response){
		JSONObject jsonObject = new JSONObject();
		List<OutStockOrder> list = deliveryNodeService.queryStockOutByUserId(Long.parseLong(userId));
		if(list.size() > 0){
			jsonObject.put("status", "1");
			jsonObject.put("data", list);
		}else{
			jsonObject.put("status", "0");
			jsonObject.put("message", "无数据");
		}
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 根据送货单ID查询所有出库单
	 * @param deliveryId	送货单ID
	 * @param response
	 */
	@RequestMapping("/queryOutStockByDeliveryId")
	public void queryOutStockByDeliveryId(String deliveryId, HttpServletResponse response){
		List<OutStockOrder> list = deliveryNodeService.queryStockOutByDeliveryId2(Long.parseLong(deliveryId));
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("status", "1");
		jsonObject.put("data", list);
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 根据出库单ID查询所有出库单详情
	 * @param orderId	出库单ID
	 * @param response
	 */
	@RequestMapping("/queryOutStockDetailByOrderId")
	public void queryOutStockDetailByOrderId(String orderId, HttpServletResponse response){
		JSONObject jsonObject = new JSONObject();
		List<OutStockOrderDetail> list = deliveryNodeService.queryOutStockDetailByOrderId(Long.parseLong(orderId));
		if(list.size() > 0){
			jsonObject.put("status", "1");
			jsonObject.put("data", list);
		}else{
			jsonObject.put("status", "0");
			jsonObject.put("message", "无数据");
		}
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 修改出库单状态
	 * @param status	出库单状态(2：配送中，3：已送达,4:已收货) 送货单状态（0：未出发，1：配送中，2：已完成）
	 * @param response
	 */
	@RequestMapping("/updateDeliveryStatus")
	public void updateDeliveryStatus(String deliveryId, String outStockId, String status, HttpServletResponse response){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String time = sdf.format(new Date());
		JSONObject jsonObject = new JSONObject();
		int result = 1;
		if("2".equals(status) && deliveryId != null && !"".equals(deliveryId)){
			int i = inventoryService.updateById(deliveryId+"", "status", "1", "llm_deliveryNode");
			if(i > 0){
				List<OutStockOrder> list = deliveryNodeService.queryStockOutByDeliveryId2(Long.parseLong(deliveryId));
				for(OutStockOrder or : list){
					int i2 = deliveryNodeService.updateById2(or.getId()+"", "status", "2", "start_date", time, "lz_out_stock_order");
					if(i2 <= 0){
						result = 0;
						break;
					}
				}
			}
		}else if("3".equals(status) && outStockId != null && !"".equals(outStockId)){
			int i = deliveryNodeService.updateById2(outStockId+"", "status", "3", "end_date", time, "lz_out_stock_order");
			if(i <= 0){
				result = 0;
			}else{
				result = 1;
			}
		}
		if(result <= 0){
			jsonObject.put("status", "0");
			jsonObject.put("message", "网络错误");
		}else{
			jsonObject.put("status", "1");
			jsonObject.put("data", "成功");
		}
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 修改出库单详情
	 * @param json
	 * @param response
	 */
	@RequestMapping("/updateOutStockDetail")
	public void updateOutStockDetail(String json, String deliveryId, String reason, HttpServletResponse response){
		JSONObject jsonObject = new JSONObject();
		int result = 0;
		if(deliveryId != null && !"".equals(deliveryId)){
			result = 1;
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String time = sdf.format(new Date());
			//json转list集合
			List<OutStockOrderDetail> list = new ArrayList<>();
			Gson gson = new Gson();
			list = gson.fromJson(json, new TypeToken<List<OutStockOrderDetail>>() {}.getType());
			for(OutStockOrderDetail detail : list){
				int i = deliveryNodeService.updateById2(detail.getId()+"", "arrival_quantity", detail.getArrival_quantity()+"", "return_quantity", (detail.getAct_num() - detail.getArrival_quantity())+"", "lz_out_stock_order_detail");
				if(i <= 0){
					result = 0;
					break;
				}
			}
			if(result == 1){
				//修改出库单状态
				deliveryNodeService.updateById3(list.get(0).getOut_stock_num_id()+"", "status", "4", "arrival_date", time, "return_reason", reason, "lz_out_stock_order");
				List<OutStockOrder> list2 = deliveryNodeService.queryStockOutByDeliveryId2(Long.parseLong(deliveryId));
				int sum = 0;
				for(OutStockOrder or : list2){
					if(or.getStatus() == 4){
						sum += 1;
					}
				}
				if(sum == list2.size()){
					inventoryService.updateById(deliveryId+"", "status", "2", "llm_deliveryNode");
				}
			}
		}
		if(result <= 0){
			jsonObject.put("status", "0");
			jsonObject.put("message", "网络错误");
		}else{
			jsonObject.put("status", "1");
			jsonObject.put("data", "成功");
		}
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
